package com.example.mqdemo.PointToPoint.normalType;

import com.example.mqdemo.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/*
 *@description: 点对点队列消息接收者普通版
 *@author: hisen
 *@Time: 2023/11/20  20:59
 */
public class PointToPointConsumer {

    private final static String QUEUE_NAME = "point_to_point";

    public static void main(String[] args) throws Exception {

        // 获取到连接以及mq通道
        Connection connection = ConnectionUtil.getConnection();
        // 从连接中创建通道
        Channel channel = connection.createChannel();
        // 声明队列
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        //3.0、4.0老版本写法，5.0新版本QueueingConsumer已废弃
        /*
            // 定义队列的消费者
            QueueingConsumer consumer = new QueueingConsumer(channel);
            // 监听队列
            channel.basicConsume(QUEUE_NAME, true, consumer);
            // 获取消息
            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                String message = new String(delivery.getBody());
                System.out.println(" [x] Received '" + message + "'");
            }
         */
        //新版本写法
        boolean autoAck=false;
        channel.basicConsume(QUEUE_NAME, autoAck, "", new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //获取消息字节、设置编码
                String message = new String(body, StandardCharsets.UTF_8);
                System.out.println("收到消息："+message);
                // 手动处理消息
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });

    }
}